import Vue from 'vue'

import router from '@/router'
import store from '@/store'

// config
import { appSetting } from '@/setting/app-setting'
import { user_login_path, whiteList } from '@/router/router-map'

// UI
import notification from 'ant-design-vue/es/notification'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// NProgress 配置
NProgress.configure({
    showSpinner: false
  }
)

router.beforeEach((to, from, next) => {
  console.info('from -->', from)
  console.info('goto -->', to)

  NProgress.start() // start progress bar

  let token = Vue.ls.get(appSetting.token_key)
  if (token) { // 有 token
    if (to.path === user_login_path) {
      // next({
      //   path: '/board/analysis'
      // })
      next({
        name: 'board'
      })
      NProgress.done()
    } else {
      if (!store.getters.hasUserInfo) { // 没有获取用户信息
        store.dispatch('userInfo').then(rules => {
          const roles = rules
          store.dispatch('generateRoutes', { roles }).then(() => { // 根据 roles 权限生成可访问的路由表
            router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          })
        }).catch(() => {
          notification.error({ message: '错误', description: '请求用户信息失败，请重试' })
          store.dispatch('logout').then(() => {
            next({ path: user_login_path })
          })
        })
      } else {
        next()
      }
    }
  } else {
    // 在免登录白名单，直接进入
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next({ path: user_login_path })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
